<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.searchKeyWord"
        clearable
        class="filter-item"
        style="width: 200px"
        placeholder="按设备类型,编号,id查找"
      />
      <el-select v-model="listQuery.room" class="filter-item" placeholder="全部机房" @change="getList" clearable>
        <el-option
          v-for="item in computerRoomList"
          :key="item.id"
          :label="item.name"
          :value="item.name"/>
      </el-select>
      <el-button
        v-permission="['equipmentManage:equipment:list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button
      >
      <el-button
        v-permission="['equipmentManage:equipment:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="switchBut()"
      >全部设备</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="switchBut(1)"
      >正常设备</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="switchBut(2)"
      >异常设备</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="switchBut(3)"
      >弃用</el-button
      >
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
    <el-table-column type="index" align="center" label="序号" width="50">
        <template scope="scope">
          <span v-if="scope.$index < 9">0{{ scope.$index + 1 }}</span>
          <span v-else>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备id" prop="id" />
      <el-table-column align="center" label="设备类型" prop="equipmentType" />
      <el-table-column align="center" label="设备编号" prop="equipmentNo" />
      <el-table-column align="center" label="所属机房" prop="roomName" />
      <el-table-column align="center" label="检查事项" prop="inspectionItems" />
      <el-table-column align="center" label="监控状态" prop="status" class="colour">
        <template scope="scope">
          <div v-if="scope.row.status === 1" style="width:100%;background-color: #3ebc37;color:#ffffff;">正常</div>
          <div v-if="scope.row.status === 2" style="width:100%;background-color: #f0541d;color:#ffffff;">异常</div>
          <div v-if="scope.row.status === 3" style="width:100%;background-color: #999999;color:#ffffff;">弃用</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding fixed-width"
        min-width="170px"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="['equipmentManage:equipment:edit']"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑</el-button
          >
          <el-button
            v-permission="['equipmentManage:equipment:delete']"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)"
          >删除</el-button
          >
          <el-button
            v-permission="['equipmentManage:equipment:edit']"
            type="primary"
            size="mini"
            @click="discard(scope.row)"
          >{{ scope.row.status === 3?"启用":"弃用" }}</el-button
          >
          <el-button
            v-permission="['equipmentManage:equipment:edit']"
            type="primary"
            size="mini"
            @click="recordClick(scope.row)"
          >记录</el-button
          >
          <el-button
            v-permission="['equipmentManage:equipment:edit']"
            type="primary"
            size="mini"
            @click="qrcode(scope.row)"
          >二维码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="id" prop="id" hidden>
          <el-input v-model="dataForm.id" />
        </el-form-item>
        <el-form-item label="设备类型" prop="equipmentType">
          <el-select
            v-model="dataForm.equipmentType"
            placeholder="请选择设备类型"
            @change="equipmentChange"
          >
            <el-option
              v-for="item in equipmentList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号" prop="equipmentNo">
          <el-input v-model="dataForm.equipmentNo" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="所属机房" prop="roomName">
          <el-select
            v-model="dataForm.roomName"
            placeholder="请选择机房类型"
            @change="computerRoomChange"
          >
            <el-option
              v-for="item in computerRoomList"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="roomId" prop="roomId">
          <el-input v-model="dataForm.roomId" />
        </el-form-item> -->
        <el-form-item label="检查事项" prop="inspectionItems">
          <el-checkbox-group v-model="form.type">
            <el-checkbox label="温度" name="type" :disabled="prohibit"/>
            <el-checkbox label="湿度" name="type" />
            <el-checkbox label="运行状态" name="type"/>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus === 'create'"
          :loading="submiting"
          type="primary"
          @click="createData"
        >确定</el-button
        >
        <el-button
          v-else
          :loading="submiting"
          type="primary"
          @click="updateData"
        >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listEquipment,
  createEquipment,
  updateEquipment,
  deleteEquipment,
  equipmentXiaLa,
  computerRoomXiaLa,
  switchEquipment
} from '@/api/equipment'
import Pagination from '@/components/Pagination'
export default {
  name: 'Equipment',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        type: '',
        searchKeyWord: '',
        room: ''
      },
      dataForm: {
        id: undefined
      },
      dialogFormVisible: false,
      submiting: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        // equipmentType: [
        //   { required: true, message: "设备类型名称不能为空", trigger: "blur" },
        // ],
        // equipmentNo: [
        //   { required: true, message: "设备编号名称不能为空", trigger: "blur" },
        // ],
        // roomName: [
        //   { required: true, message: "所属机房名称不能为空", trigger: "blur" },
        // ],
        // roomId: [
        //   { required: true, message: "roomId名称不能为空", trigger: "blur" },
        // ],
        // inspectionItems: [
        //   { required: true, message: "检查事项名称不能为空", trigger: "blur" },
        // ],
      },
      checkList: [],
      form: {
        type: []
      },
      equipmentList: [],
      computerRoomList: [],
      prohibit:false

    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listEquipment(this.listQuery)
        .then((response) => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      computerRoomXiaLa()
        .then((response) => {
          // 机房类型下拉
          this.computerRoomList = response.data.data
        })
    },
    qrcode(val) {
      window.open(val.code)
    },
    switchBut(num) {
      this.listQuery.type = num
      this.getList()
    },
    recordClick(row){
        this.$router.push({
        path: 'recordPage',
        query: {obj: JSON.stringify(row)}
      })

    },
    checkboxChange(e) {
      this.dataForm.runningStatus = e[0]
    },
    discard(val) {
      this.$confirm(val.status === 3 ? '确定该设备重新启用' : '确定该设备暂不启用', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        switchEquipment({ id: val.id, flag: val.status === 3 ? '1' : '2' })
          .then((response) => {
            this.list.unshift(response.data.data)
            this.dialogFormVisible = false
            this.$notify.success({
              title: '成功',
              message: val.status === 3 ? '启用成功' : '弃用成功'
            })
            this.getList()
            this.submiting = false
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
            this.submiting = false
          })
      })
    },
    xialaInfo() {
      equipmentXiaLa()
        .then((response) => {
          // 设备类型下拉
          this.equipmentList = response.data.data
        })
    },
    computerRoomChange(e) {
      this.dataForm.roomId = e.id
      this.dataForm.roomName = e.name
    },
     equipmentChange(e){
      if(e=="空调" || e== "电池组"){
        this.form.type = ['温度']
        this.prohibit = true
      }else{
          this.prohibit = false
      }
     },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined
      }
    },
    handleCreate() {
      this.prohibit = false
      this.xialaInfo()
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      if (!this.dataForm.equipmentType) {
        this.$message.error('请选择设备类型！')
        return
      }
      if (!this.dataForm.equipmentNo) {
        this.$message.error('请输入设备编号！')
        return
      }
      if (!this.dataForm.roomName) {
        this.$message.error('请选择所属机房！')
        return
      }
      if (!this.dataForm.equipmentType) {
        this.$message.error('请选择设备类型！')
        return
      }
      if (this.form.type.length == 0) {
        this.$message.error('请选择所要检查的事项！')
        return
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submiting = true
          this.dataForm.inspectionItems = this.form.type.toString()
          createEquipment(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.getList()
              this.$notify.success({
                title: '成功',
                message: '添加成功'
              })
              this.submiting = false
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
              this.submiting = false
            })
        }
      })
    },
    handleUpdate(row) {
      this.xialaInfo()
      this.dataForm = Object.assign({}, row)
      if(row.equipmentType == '空调' || row.equipmentType == '电池组'){
        this.prohibit = true
      }
      this.form.type = row.inspectionItems.split(",")
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      if (!this.dataForm.equipmentType) {
        this.$message.error('请选择设备类型！')
        return
      }
      if (!this.dataForm.equipmentNo) {
        this.$message.error('请输入设备编号！')
        return
      }
      if (!this.dataForm.roomName) {
        this.$message.error('请选择所属机房！')
        return
      }
      if (!this.dataForm.equipmentType) {
        this.$message.error('请选择设备类型！')
        return
      }
      if (this.form.type.length === 0) {
        this.$message.error('请选择所要检查的事项！')
        return
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submiting = true
          this.dataForm.inspectionItems = this.form.type.toString()
          updateEquipment(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.submiting = false
              this.getList()
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
              this.submiting = false
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm(
        '此操作将永久删除该记录---' + row.id + '---, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          deleteEquipment(row.id)
            .then((response) => {
              this.$notify.success({
                title: '成功',
                message: '删除成功'
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        })
        .catch(() => {
          return false
        })
    }
  }
}
</script>
<style scoped>
::v-deep .el-table__body tr .colour{
  background: red;
}


</style>
